<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 定时任务
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-input v-model="query.name" placeholder="任务名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" @click="addTasksModel = true">新增任务</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="id" width="55" align="center"></el-table-column>
                <el-table-column prop="name" label="任务名称"></el-table-column>
                <el-table-column prop="tester" width="80" label="创建人"></el-table-column>
                <el-table-column
                    label="是否启用"
                    width="80"
                    align="center">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            @change=changeSwitch(scope.row)>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="strategy" label="执行规则"></el-table-column>
                <el-table-column prop="project" label="所属项目"></el-table-column>
                <el-table-column prop="desc" label="简要描述"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleRun(scope.$index, scope.row)"
                        >运行</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 运行环境框 -->
        <el-dialog title="选择任务运行环境" :visible.sync="runVisible" width="30%">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="运行环境">
                    <el-select v-model="formv.env_id" placeholder="选择环境" style="width:100%">
                        <el-option v-for="item in envs"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="runTasks">运 行</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑定时任务" :visible.sync="editVisible" width="40%">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="任务名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="是否开启">
                    <el-switch v-model="form.status"></el-switch>
                    <el-input placeholder="* * * * *" v-model="form.strategy" style="width: 300px; margin-left: 50px">
                        <template slot="prepend">执行规则</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="负责人">
                    <el-input v-model="form.tester"></el-input>
                </el-form-item>
                <el-form-item label="所属项目">
                    <el-input v-model="form.project" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item :label="`已选${(casenumber)}用例`">
                    <el-tree
                        style="width:300px"
                        :data="cases"
                        show-checkbox
                        node-key="mid"
                        ref="tree"
                        :default-checked-keys="form.caseset"
                        @check-change="handleCheckChange"
                        :props="defaultProps">
                    </el-tree>
                </el-form-item>
                <el-form-item label="运行环境">
                    <el-select v-model="form.env_id" placeholder="选择环境" style="width:100%">
                        <el-option v-for="env in envs"
                            :key="env.id"
                            :label="env.name"
                            :value="env.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮件地址">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="简要描述">
                    <el-input v-model="form.desc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增任务弹框 -->
        <el-dialog title="新增定时任务" :visible.sync="addTasksModel" width="40%">
            <el-form ref="form" :model="form" label-width="80px">
                <el-form-item label="任务名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="是否开启">
                    <el-switch v-model="form.status"></el-switch>
                    <el-input placeholder="* * * * *" v-model="form.strategy" style="width: 300px; margin-left: 50px">
                        <template slot="prepend">执行规则</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="负责人">
                    <el-input v-model="form.tester"></el-input>
                </el-form-item>
                <el-form-item label="所属项目">
                    <el-select v-model="form.project_id" placeholder="选择项目" @change="getModuleByProject" style="width:100%">
                        <el-option v-for="item in projects"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                            :project_id="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="`已选${(casenumber)}用例`">
                    <el-tree
                        style="width:300px"
                        :data="cases"
                        show-checkbox
                        node-key="mid"
                        ref="tree"
                        @check-change="handleCheckChange"
                        :props="defaultProps">
                    </el-tree>
                </el-form-item>
                <el-form-item label="运行环境">
                    <el-select v-model="form.env_id" placeholder="选择环境" style="width:100%">
                        <el-option v-for="item in envs"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                            :env_id="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮件地址">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="简要描述">
                    <el-input v-model="form.desc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { tasks_list } from '../../api/api';
import { edits_tasks, edit_tasks } from '../../api/api';
import { add_tasks } from '../../api/api';
import { projects_names } from '../../api/api';
import { delete_tasks} from '../../api/api';
import { run_tasks } from '../../api/api';
import { nameAndid_in_envs, p_models_and_cases } from '../../api/api'

export default {
    name: 'tasks',
    data() {
        return {
            query: {
                page: 1,
                size: 10
            },
            value: [],
            envs: [],
            projects: [],
            cases: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            casenumber: 0,
            addTasksModel: false,
            runVisible: false,
            editVisible: false,
            pageTotal: 0,
            form: {
                status: false,
                strategy: '* * * * *',
                caseset: [],
            },
            formv: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData()
        this.getProjects()
        this.getEnvs()
    },
    methods: {
        // 请求任务列表数据
        getData() {
            tasks_list(this.query)
                .then((response)=> {
                    this.tableData = response.data.results
                    this.pageTotal = response.data.count
            });
        },
        //获取运行环境列表
        getEnvs(){
            nameAndid_in_envs()
                .then((response)=> {
                    this.envs = response.data
                })
        },
        // 获取项目列表
        getProjects() {
            projects_names()
                .then(response => {
                    this.projects = response.data;
                })
        },
        // 获取某项目下的所有模块及用例
        getModuleByProject(id) {
            p_models_and_cases(id)
                .then(response => {
                    this.cases = response.data
                })
                .catch(error => {
                    this.$message.error('根据项目id获取模块失败')
                })
        },
        // 获取所选中的用例ID
        handleCheckChange(){
            // console.log(this.$refs.tree.getCheckedKeys());     
            let res = this.$refs.tree.getCheckedNodes()
            let arr = []
            res.forEach((item) => {
                if(item.cid != undefined){
                    arr.push(item.cid)
                }
            })
            this.form.caseset = arr
            this.casenumber = parseInt(arr.length)
        },
        // 修改任务状态
        changeSwitch(row) {

            edit_tasks(row.id,{status: row.status})
                .then(res => {
                    this.getData()
                    if(row.status){
                        this.$message.success("开启成功！")
                    }else{
                        this.$message.success("关闭成功！")
                    }
                    
                })
                .catch({
                });
        },
        // 运行操作
        handleRun(index, row) {
            this.tasks_id = row.id
            this.runVisible = true
        },
        // 运行任务
        runTasks(){
            run_tasks(this.tasks_id, this.formv)
                .then((response) => {
                    this.runVisible = false
                    this.$message.success("任务开始运行")
                    this.$router.push({
                        path: '/reportsdetails',
                        query: {
                            id: response.data.id
                        }
                    })
                })
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'page', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            this.tasks_id = row.id;
            this.tasks_name = row.name;
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    delete_tasks(this.tasks_id)
                    .then(response => {
                        this.$message.success(`删除成功: ${this.tasks_name}`);
                        this.tableData.splice(index, 1);
                    }).catch(error => {});
                }).catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.tasks_idx = index;
            this.tasks_id = row.id;
            this.getModuleByProject(row.project_id);
            this.form = row;
            this.form.caseset = JSON.parse(this.form.caseset);
            this.form.env_id = parseInt(this.form.env_id);
            this.casenumber = this.form.caseset.length;
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.form.caseset = JSON.stringify(this.form.caseset)
            edits_tasks(this.tasks_id, this.form)
            .then(response => {
                this.editVisible = false;
                this.$message.success(`修改 ${this.form.name} 成功`);
                this.$set(this.tableData, this.tasks_idx, this.form);
            })
            .catch(error => {
                this.$message.error("所有字段为必填项")
            })
        },
        // 新增任务
        saveAdd(){
            this.form.caseset = JSON.stringify(this.form.caseset)
            add_tasks(this.form)
                .then(response => {
                    this.addTasksModel = false;
                    this.$message.success(`添加成功：${this.form.name}`);
                    this.getData();
                    this.$set(this.tableData, this.tasks_idx, this.form);
                })
                .catch(error => {
                    this.$message.error("所有字段为必填项");
                })
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
